<script lang="ts" setup>
import { FormInstance } from 'element-plus';
import Creation from '@/views/book/creation.vue';
import Detail from '@/views/book/detail.vue';
import { useHeaderStore } from '@/stores/header';
import { MatchItem, OrderItem, Page, Book } from '@/model';
import { deleteBook, pageBook } from '@/api';

const headerStore = useHeaderStore();
// 检索条件的表单
const schForm = ref<Book>({
  id: '',
  bookName: '',
  bookCode: '',
  receiptDate: '',
  remark: '',
});
const searchRef = ref<FormInstance>();
// 表格分页数据
const tableData = ref<Page<Book>>({
  records: [] as Book[],
  current: 0,
  pages: 0,
  size: 0,
  total: 0,
});
const visible = ref<boolean>(false);
const openType = ref<string>('');
const currentRow = ref<Book>();

const detailsVisible = ref<boolean>(false);

// 分页请求参数
const pageParam = ref<Page<Book>>({
  current: 1,
  size: 10,
  orderItems: new Array<OrderItem>({
    column: 'createAt',
    asc: false,
  }),
});

/**
 * 分页请求
 * @param pageObj 分页请求信息
 */
const pageReq = (pageObj: Page<Book>) => {
  pageBook(pageObj).then((res) => {
    if (res.records && res.records.length) {
      tableData.value.records = res.records;
      tableData.value.current = Number(res.current);
      tableData.value.pages = Number(res.pages);
      tableData.value.size = Number(res.size);
      tableData.value.total = Number(res.total);
    } else {
      tableData.value.records = [];
    }
  });
};

/**
 * 关闭弹窗时调用
 * @param open
 * @param type 单开弹窗的类型
 * @param row 当前行
 */
const onCloseDialog = (open: boolean, type: string, row: Book | undefined) => {
  visible.value = open;
  openType.value = type;
  currentRow.value = row;
};

/**
 * 关闭详情弹窗时
 */
const onDetailsClose = () => {
  detailsVisible.value = false;
};

/**
 * 初始化分页请求参数
 */
const initPageParam = () => {
  pageParam.value = {
    current: 1,
    size: 10,
    orderItems: new Array<OrderItem>({
      column: 'createAt',
      asc: false,
    }),
  };
};

/**
 * 检索
 */
const onSearch = () => {
  if (!schForm.value) {
    return;
  }
  const matchItems = [];
  if (schForm.value.bookName) {
    matchItems.push(<MatchItem>{
      column: 'name',
      value: schForm.value.bookName,
      and: true,
      operator: 'LIKE',
    });
  }
  pageParam.value = {
    current: 1,
    size: 10,
    orderItems: new Array<OrderItem>({
      column: 'createAt',
      asc: false,
    }),
    matchItems,
  };
  pageReq(pageParam.value);
};

/**
 * 重置检索条件
 */
const onResetSchFrom = () => {
  initPageParam();
  pageReq(pageParam.value);
  if (!searchRef || !searchRef.value) return;
  searchRef.value.resetFields();
};

/**
 * 点击删除
 * @param row
 */
const onDelete = (row: Book) => {
  deleteBook(row.id).then(() => pageReq(pageParam.value));
};

/**
 * 点击编辑
 * @param row
 */
const onEdit = (row: Book) => {
  onCloseDialog(true, 'update', row);
};

/**
 * 点击详情
 * @param row
 */
const onDetails = (row: Book) => {
  detailsVisible.value = true;
  currentRow.value = row;
};

/**
 * 点击新增
 * @param row
 */
const onCreate = (row: Book | undefined) => {
  onCloseDialog(true, 'create', row);
};

/**
 * 新增或编辑提交后调用
 */
const onSubmitted = () => {
  onCloseDialog(false, '', undefined);
  initPageParam();
  pageReq(pageParam.value);
};

/**
 * 动态计算表格高度
 */
const tableHeight = computed(() => {
  return window.innerHeight - 360;
});

// 监听当前页变化，请求数据
watch(
  () => tableData.value.current,
  () => {
    pageParam.value.current = tableData.value.current;
    pageReq(pageParam.value);
  },
  { deep: true },
);

onMounted(() => {
  headerStore.$patch({
    title: '礼簿管理',
  });
  initPageParam();
  pageReq(pageParam.value);
  onCloseDialog(false, '', undefined);
});
</script>

<template>
  <div class="content-container">
    <!--搜索栏-->
    <div class="search-container">
      <el-scrollbar height="100px">
        <el-form
          ref="searchRef"
          :inline="true"
          :model="schForm"
          class="form-search"
          size="large"
        >
          <el-form-item>
            <el-input
              class="input-search"
              v-model="schForm.bookName"
              placeholder="按名称搜索"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-tooltip content="搜索" placement="top" effect="light" :show-after="500">
              <el-button @click="onSearch" class="btn-search">
                <el-icon size="18px">
                  <i-ep-search />
                </el-icon>
              </el-button>
            </el-tooltip>
          </el-form-item>
          <el-form-item>
            <el-tooltip content="重置" placement="top" effect="light" :show-after="500">
              <el-button @click="onResetSchFrom" class="btn-reset">
                <el-icon size="18px">
                  <i-ep-refresh-left />
                </el-icon>
              </el-button>
            </el-tooltip>
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </div>
    <!--功能栏-->
    <div class="function-container">
      <span class="title">礼簿列表</span>
      <el-tooltip content="新增礼簿" placement="top" effect="light" :show-after="500">
        <el-button class="btn-create" circle @click="onCreate(undefined)">
          <el-icon>
            <i-ep-plus />
          </el-icon>
        </el-button>
      </el-tooltip>
    </div>
    <!--数据栏-->
    <div class="data-container">
      <el-table :data="tableData.records" :height="tableHeight">
        <el-table-column type="index" width="55" label="序号" />
        <el-table-column
          prop="bookName"
          label="礼簿名称"
          :show-overflow-tooltip="true"
        />
        <el-table-column prop="bookCode" label="礼簿编码" min-width="160" />
        <el-table-column prop="receiptDate" label="收礼日期" min-width="120" />
        <el-table-column
          prop="remark"
          label="备注"
          min-width="160"
          :show-overflow-tooltip="true"
        />
        <el-table-column prop="operate" label="操作" width="160" :fixed="'right'">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top" effect="light" :show-after="500">
              <el-button class="btn-edit" circle @click="onEdit(scope.row)">
                <i-ep-edit />
              </el-button>
            </el-tooltip>
            <el-tooltip content="详情" placement="top" effect="light" :show-after="500">
              <el-button class="btn-details" circle @click="onDetails(scope.row)">
                <i-ep-document />
              </el-button>
            </el-tooltip>
            <el-popconfirm
              title="确定删除？"
              confirm-button-text="确定"
              cancel-button-text="取消"
              cancel-button-type="success"
              confirm-button-type="danger"
              @confirm="onDelete(scope.row)"
            >
              <template #reference>
                <el-button class="btn-delete" circle>
                  <i-ep-delete />
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :background="true"
        v-model:current-page="tableData.current"
        v-model:page-size="tableData.size"
        :total="tableData.total"
        :page-count="tableData.pages"
        :pager-count="5"
        layout="prev, pager, next"
        class="table-pagination"
      >
      </el-pagination>
    </div>
    <!--弹窗-新增/编辑-->
    <creation
      :visible="visible"
      :current-row="currentRow"
      :type="openType"
      @close-dialog="onCloseDialog"
      @submitted="onSubmitted"
    />
    <!--弹窗-详情-->
    <detail
      :visible="detailsVisible"
      :current-row="currentRow!"
      @close-dialog="onDetailsClose"
    />
  </div>
</template>

<style lang="scss" scoped></style>
